from pathlib import PurePosixPath
from django.conf import settings
from django.utils import html
from django.contrib import admin
from django.utils.html import format_html

from .models import TestTask

@admin.register(TestTask)
class TestTaskAdmin(admin.ModelAdmin):
    list_display = ('name', 'test_type', 'status', 'is_pass', 'has_report', 'report_url', 'created_at', 'updated_at')
    list_filter = ('status', 'is_pass', 'is_processing', 'has_report', 'test_type')
    search_fields = ('name',)

    def report_url(self, obj: TestTask):
        if obj.status == 3 and obj.has_report:
            case_path = PurePosixPath(str(obj.case_file))
            root_path = PurePosixPath(settings.MEDIA_URL)
            report_path = root_path / case_path.parent / 'report/index.html'
            return html.format_html(f'<a href="{report_path}" target="_blank">点击查看</a>')
        return "无报告"

    report_url.short_description = '测试报告'